package com.renrendoc.network.flow.util;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketClient {
    private static final String SERVER_IP = PropertiesUtil.getProperty("rpc.address");
    private static final int SERVER_PORT = Integer.parseInt(PropertiesUtil.getProperty("rpc.port")) ;
    private static final int TIMEOUT = 1000;
    private static final Gson gson = new Gson();

    public static Map<String, Object> callRemoteMethod(Map<String, Object> params) throws Exception {
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        Map<String, Object> responseData = null;
        try {
            // 连接到远程服务器
            socket = new Socket();// SERVER_IP, SERVER_PORT
            socket.connect(new java.net.InetSocketAddress(SERVER_IP, SERVER_PORT), TIMEOUT);

            // 获取输出流，用于向服务器发送数据
            out = new PrintWriter(socket.getOutputStream(), true);

            // 封装请求数据为 JSON 格式
            String requestDataJson = gson.toJson(params);

            // 发送请求数据到服务器
            out.println(requestDataJson);

            // 获取输入流，用于接收从服务器发送过来的数据
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 读取服务器响应
            String responseJson = in.readLine();

            // 解析服务器响应
            Map<String, Object> response = gson.fromJson(responseJson, Map.class);
            if (null != response) {
                String orDefault = response.getOrDefault("code", "err").toString();
                if (!"err".equals(orDefault)) {
                    int code = ((Number) response.get("code")).intValue(); // 改为使用 Number 类型

                    if (code == 0) {
                        Object data = response.get("data");
                        if (data instanceof Map) {
                            responseData = (Map<String, Object>) data;
                        }
                    }

                } else {
                    throw new Exception("Error response from server: " + responseJson);
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭连接
            try {
                if (out != null) out.close();
                if (in != null) in.close();
                if (socket != null) socket.close();
            } catch (Exception e) {
                throw e;
            }
        }
        return responseData;
    }
    public static Map<String, Object> createRequestParams(String clazz, String method, Object[] paramArray, String project) {
        // 创建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("class", clazz);
        params.put("method", method);
        params.put("param_array", paramArray);
        params.put("project", project);
        return params;
    }


    public static void main(String[] args) {
        // 封装请求参数
        Map<String, Object> params = createRequestParams("RenrenV2\\EventTracking\\ETClickEventStatService", "addData", new Object[]{

        }, "myProject");

        try {
            // 调用远程方法
            Map<String, Object> responseData = callRemoteMethod(params);
            System.out.println("Response data from server: " + responseData.get("aid"));
        } catch (Exception e) {
            System.out.println("Exception occurred: " + e.getMessage());
        }

        // 封装请求参数
        Map<String, Object> params1 = createRequestParams("Doc\\BookResourcesUrl", "getOneDataToCronByAid", new Object[]{2}, "myProject");

        try {
            // 调用远程方法
            Map<String, Object> responseData = callRemoteMethod(params1);
            System.out.println("Response data from server: " + responseData.get("aid"));
        } catch (Exception e) {
            System.out.println("Exception occurred: " + e.getMessage());
        }
    }

}
